# 封装分类获取方法
from goods.models import GoodsChannel


def get_categories():
    # 定义字典
    categories = {}
    # 查询所有的频道组
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 遍历频道组，组装数据
    for channel in channels:
        # 取出组的编号
        group_id = channel.group_id
        # 组装好一个分类的字典
        if group_id not in categories:
            categories[group_id] = {"channels": [], "sub_cats": []}
        # 添加一级分类到channels
        category = channel.category
        category_dict = {
            "id": category.id,
            "name": category.name,
            "url": channel.url
        }
        categories[group_id]["channels"].append(category_dict)
        # 添加二级、三级分类
        for cat2 in category.subs.all():
            categories[group_id]["sub_cats"].append(cat2)
    return categories
